package com.weetop.aklyscan.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.honeywell.aidc.AidcManager;
import com.honeywell.aidc.BarcodeFailureEvent;
import com.honeywell.aidc.BarcodeReadEvent;
import com.honeywell.aidc.BarcodeReader;
import com.honeywell.aidc.TriggerStateChangeEvent;
import com.weetop.aklyscan.R;
import com.weetop.aklyscan.appConfig.MyApplication;
import com.weetop.aklyscan.base.BaseActivity;
import com.weetop.aklyscan.base.mvp.BasePresenter;
import com.weetop.aklyscan.utils.Tablayout.SegmentTabLayout;
import com.weetop.aklyscan.utils.Tablayout.listener.OnTabSelectListener;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class NewScanInStockActivity extends BaseActivity implements BarcodeReader.BarcodeListener, BarcodeReader.TriggerListener {

    @BindView(R.id.tl_1)
    SegmentTabLayout tl1;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.title)
    TextView titleView;
    @BindView(R.id.frame_scan_search)
    FrameLayout frameScanSearch;
    int page = 0;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    private String[] mTitles1 = {"装箱", "入库"};
    private String[] mTitles2 = {"入库"};
    private Fragment[] fragments1;

    private Fragment_zx_op fragment_zx;
    private Fragment_in_wx fragment_in_wx;
    private Fragment_in_wx fragment_in_wx1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_in_stock);
        ButterKnife.bind(this);
        fragment_zx = new Fragment_zx_op();
        fragment_in_wx = new Fragment_in_wx();
        fragment_in_wx1 = new Fragment_in_wx();
        if (MyApplication.getPort().equals("1")) {
            tl1.setTabData(mTitles1);
            titleView.setText("扫码入库");
            fragments1 = new Fragment[]{fragment_zx, fragment_in_wx};
            tl1.setOnTabSelectListener(new OnTabSelectListener() {
                @Override
                public void onTabSelect(int position) {
                    page = position;
                    switchfragment(fragments1[position]);
                }

                @Override
                public void onTabReselect(int position) {

                }
            });
            switchfragment(fragment_zx);
        } else {
            titleView.setText("配件入库");
            tl1.setTabData(mTitles2);
            tl1.setVisibility(View.GONE);
            fragments1 = new Fragment[]{fragment_in_wx};
            tl1.setOnTabSelectListener(new OnTabSelectListener() {
                @Override
                public void onTabSelect(int position) {
                    page = position;
                    switchfragment(fragments1[position]);
                }

                @Override
                public void onTabReselect(int position) {

                }
            });
            switchfragment(fragment_in_wx);
        }

        initScan();
    }

    /**
     * 选择fragment
     *
     * @param fragment
     */
    private void switchfragment(Fragment fragment) {
        // 设置一个默认值
        if (fragment == null) {
            if (MyApplication.getPort().equals("1")) {
                fragment = fragment_zx;
            } else {
                fragment = fragment_in_wx;
            }
        }
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        for (Fragment fragment1 : fragments1) {
            if (fragment1 != fragment) {
                if (fragment1 != null && !fragment1.isHidden() && fragment1.isAdded()) {
                    ft.hide(fragment1);
                }
            }
        }

        if (fragment.isAdded() && fragment.isHidden()) {
            ft.show(fragment);
        } else {
            if (!fragment.isAdded()) {
                ft.add(R.id.frame_scan_search, fragment);
            }
        }
        ft.commitAllowingStateLoss();
    }

    @OnClick(R.id.iv_back)
    public void onViewClicked() {
        AlertDialog.Builder normalDialog = new AlertDialog.Builder(NewScanInStockActivity.this);
        normalDialog.setTitle("提示");
        normalDialog.setMessage("返回主页，当前数据将清除，是否返回");
        normalDialog.setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                finish();
            }
        });
        normalDialog.setNegativeButton("否", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        normalDialog.create().show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            AlertDialog.Builder normalDialog = new AlertDialog.Builder(NewScanInStockActivity.this);
            normalDialog.setTitle("提示");
            normalDialog.setMessage("返回主页，当前数据将清除，是否返回");
            normalDialog.setPositiveButton("是", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    finish();
                }
            });
            normalDialog.setNegativeButton("否", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            normalDialog.create().show();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }

    }


    AidcManager manager;
    BarcodeReader barcodeReader;

    private void initScan() {
        //第一步：获取扫描资源，设置扫描参数，开启扫描功能
        AidcManager.create(NewScanInStockActivity.this, new AidcManager.CreatedCallback() {
            @Override
            public void onCreated(AidcManager aidcManager) {
                manager = aidcManager;
                barcodeReader = manager.createBarcodeReader();
                try {
                    //设置扫描参数
//                    barcodeReader.setProperty(BarcodeReader.PROPERTY_CODE_128_ENABLED, true); //开启Code128码制
//                    barcodeReader.setProperty(BarcodeReader.PROPERTY_EAN_13_ENABLED, false); //关闭EAN13码制
//                    barcodeReader.setProperty(BarcodeReader.PROPERTY_TRIGGER_CONTROL_MODE, BarcodeReader.TRIGGER_CONTROL_MODE_CLIENT_CONTROL); //设置手动触发模式

                    barcodeReader.claim(); //开启扫描功能
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //第二步：添加侧面扫描键事件监听和条码事件监听
                barcodeReader.addTriggerListener(NewScanInStockActivity.this);
                barcodeReader.addBarcodeListener(NewScanInStockActivity.this);
            }
        });
    }

    @Override
    public void onBarcodeEvent(BarcodeReadEvent barcodeReadEvent) {
        String barcodeData = barcodeReadEvent.getBarcodeData();
        if (MyApplication.getPort().equals("1")) {
            if (page == 0) {
                ((Fragment_zx_op) fragments1[0]).onBarcodeEvent(barcodeData);
            } else {
                ((Fragment_in_wx) fragments1[1]).onBarcodeEvent(barcodeData);
            }
        } else {
            ((Fragment_in_wx) fragments1[0]).onBarcodeEvent(barcodeData);
        }
    }

    @Override
    public void onFailureEvent(BarcodeFailureEvent barcodeFailureEvent) {
        System.out.println("失败：");
    }

    @Override
    public void onTriggerEvent(TriggerStateChangeEvent triggerStateChangeEvent) {
        System.out.println("按键：");
        if (triggerStateChangeEvent.getState() == true) {
            try {
                barcodeReader.light(true);        //开启补光
                barcodeReader.aim(true);        //开启瞄准线
                barcodeReader.decode(true);        //开启解码
            } catch (Exception e) {
                Toast.makeText(NewScanInStockActivity.this, "开启扫描失败", Toast.LENGTH_SHORT).show();
            }
        } else if (triggerStateChangeEvent.getState() == false) {
            try {
                barcodeReader.light(false);        //关闭补光
                barcodeReader.aim(false);        //关闭瞄准线
                barcodeReader.decode(false);    //关闭解码
            } catch (Exception e) {
                Toast.makeText(NewScanInStockActivity.this, "关闭扫描失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (barcodeReader != null) {
            try {
                barcodeReader.claim();        //开启扫描功能
            } catch (Exception e) {
//                Toast.makeText(this, "开启扫描失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (barcodeReader != null) {
            barcodeReader.release();        //释放扫描资源
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (barcodeReader != null) {
            barcodeReader.removeBarcodeListener(this);
            barcodeReader.removeTriggerListener(this);
            barcodeReader.close();
        }
        if (manager != null) {
            manager.close();
        }
    }
}
